/*
 * Copyright (C) 2020 Jimmy Hogoboom
 *
 * This file is part of Limitlist.
 *
 * Limitlist is free software: you can redistribute it and/or modify
 * it under the terms of the Affero GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Limitlist is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Affero GNU General Public License for more details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * along with Limitlist.  If not, see <https://www.gnu.org/licenses/>.
 */

// SPDX-License-Identifier: AGPL-3.0-or-later

import React, { ChangeEvent, MouseEvent, useState, useEffect } from 'react';
import CurrencyInput from 'components/CurrencyInput';
import './ProductListItem.scss';
import { ProductListItemInput } from './types';
import { calculateTotal, currencyLabel } from 'utils';

export interface ItemProps {
  value: ProductListItemInput,
  className: string,
  editing?: boolean,
  onChange: (item: ProductListItemInput) => void,
  onDelete: (item: ProductListItemInput) => void,
}

const ProductListItem: React.FC<ItemProps> = (props) => {
  const [editing, setEditing] = useState(props.editing);
  const [item, setItem] = useState(props.value as ProductListItemInput);
  const [total, setTotal] = useState()
  useEffect(() => {
    setTotal(calculateTotal(item.price, item.quantity));
  }, [item]);

  const updateItem = (property: string, value: any) => {
    setItem(item => ({ ...item, [property]: value }));
  };

  const handleNameChange = (e: ChangeEvent<HTMLInputElement>) => {
    updateItem('name', e.target.value);
  };

  const handlePriceChange = (e: ChangeEvent<HTMLInputElement>) => {
    updateItem('price', e.target.value);
  };

  const handleQuantityChange = (e: ChangeEvent<HTMLInputElement>) => {
    updateItem('quantity', Number(e.target.value) ? Number(e.target.value).toString() : '0');
  };

  const handleWrapperClick = () => setEditing(true);

  const handleSaveClick = (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    props.onChange({
      ...item,
      price: item.price
        ? item.price.replace('$', '')
        : '',
    });
    setEditing(false);
  };

  const handleCancelClick = (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    setItem(props.value);
    setEditing(false);

    if (props.value.name === ''
      && (props.value.price === '' || props.value.price === undefined)
      && (props.value.quantity === '' || props.value.quantity === undefined)
    ){
      props.onDelete(item);
    }
  };

  const handleDeleteClick = (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    props.onDelete(item);
  };

  const inputs = (
    <>
      <div
        className="field is-grouped"
      >
        <div className="control">
          <input
            type="text"
            className="input name"
            title="Product Name"
            placeholder="Product Name"
            value={item.name}
            onChange={handleNameChange}
          />
        </div>
        <div className="control">
          <input
            type="text"
            className="input quantity"
            title="Quantity"
            placeholder="Quantity"
            inputMode="decimal"
            value={item.quantity}
            onChange={handleQuantityChange}
          />
        </div>
        <div className="control">
          <CurrencyInput
            className="input price"
            title="Price"
            placeholder="Price"
            value={item.price ? item.price : ''}
            onChange={handlePriceChange}
          />
        </div>
        <div className="control">
          <CurrencyInput
            className="input total is-static"
            title="Total"
            value={total}
            readOnly
          />
        </div>
      </div>

      <div
        className="buttons"
      >
        <button
          className="button is-primary"
          disabled={!item.name && !item.price && !item.quantity}
          onClick={handleSaveClick}
        >
          <span className="icon is-small">
            <i className="fas fa-check"></i>
          </span>
          <span>Save</span>
        </button>
        <button
          className="button"
          onClick={handleCancelClick}
        >
          Cancel
        </button>
        <button
          className="button is-danger is-outlined is-pulled-right"
          onClick={handleDeleteClick}
        >
          <span>Delete</span>
          <span className="icon is-small">
            <i className="fas fa-times"></i>
          </span>
        </button>
      </div>
    </>
  );

  const labels = (
    <div
      className="columns is-mobile clickable"
    >
      <div className="column" title="Product Name">{props.value.name}</div>
      <div className="column is-narrow" title="Quantity">{props.value.quantity}</div>
      <div className="column is-narrow" title="Price">{currencyLabel(props.value.price)}</div>
      <div className="column is-narrow" title="Total">
        {currencyLabel(calculateTotal(props.value.price, props.value.quantity))}
      </div>
    </div>
  );

  const content = editing ? inputs : labels;

  return (
    <div
      className={props.className}
      onClick={handleWrapperClick}
    >
      {content}
    </div>
  );
}

export default ProductListItem;
